package com.combetter.changxing.adapter.base;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by Mark.fan on 2018/5/9.
 */

public abstract class BaseAdapter<T, V extends ViewDataBinding> extends RecyclerView.Adapter {
    protected Context mContext;

    protected List<T> mList;

    private int mLayoutRes;

    public BaseAdapter(Context c) {
        mContext = c;
        mLayoutRes = setLayout();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        V binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), mLayoutRes, parent, false);
        return new MyViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        MyViewHolder viewHolder = (MyViewHolder) holder;
        toBinding((V) viewHolder.mBinding, mList.get(position));
        viewHolder.mBinding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return (mList == null) ? 0 : mList.size();
    }

    public void setList(List<T> list) {
        mList = list;
        notifyDataSetChanged();
    }

    /**
     * 绑定数据
     * @param binding
     * @param entity
     */
    public abstract void toBinding(V binding, T entity);

    /**
     * 设置Item的布局
     * @return
     */
    public abstract int setLayout();

    static class MyViewHolder extends RecyclerView.ViewHolder{
        ViewDataBinding mBinding;

        public MyViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.mBinding = binding;
        }
    }
}
